/*
 This file is part of WebHUD.

 WebHUD is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 any later version.

 WebHUD is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with WebHUD.  If not, see <http://www.gnu.org/licenses/>.
 */

#import "WHController.h"
#import "Constants.h"
#import "Safari.h"
#import "WHApi.h"
#import "WHHelper.h"
#import "LocationChangeHandler+WHWebFrameLoadDelegate.h"

@implementation WHController

@synthesize panel;
@synthesize webview;
@synthesize tabview;
@synthesize urls;
@synthesize order;

+ (void)initialize
{
    // Force the creation of the singleton
    [WHController sharedController];
}

static WHController *sharedController = nil;

+ (WHController*)sharedController
{
    @synchronized(self) {
        if (sharedController == nil) {
            [[self alloc] init];
        }
    }
    return sharedController;
}

+ (id)allocWithZone:(NSZone *)zone
{
    @synchronized(self) {
        if (sharedController == nil) {
            sharedController = [super allocWithZone:zone];
            return sharedController;
        }
    }
    return nil;
}

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

- (id)retain
{
    return self;
}

- (unsigned)retainCount
{
    return UINT_MAX;
}

- (void)release
{
    // do nothing
}

- (id)autorelease
{
    return self;
}

- (BOOL)loadMyNibFile
{
    // The myNib file must be in the bundle that defines self's class.
    if (![NSBundle loadNibNamed:@"WebHUD" owner:self])
    {
        NSLog(@"Warning! Could not load 'WebHUB' nib file.\n");
        return NO;
    }
    return YES;
}


- (id)init
{
    self = [super init];
    if (self != nil) {

        if (!([[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.apple.Safari"] ||
              [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"org.webkit.nightly.WebKit"]
              ))
            return nil;

        NSFileManager *fm = [NSFileManager defaultManager];
        NSString *applicationSupportFolderPath = [WHPaths applicationSupportFolderPath];

        NSMutableDictionary *defaults = [NSMutableDictionary dictionaryWithContentsOfFile:
                                         [[NSBundle bundleWithIdentifier:BundleIdentifier] pathForResource:@"Defaults" ofType:@"plist"]];

        [[NSUserDefaults standardUserDefaults] registerDefaults:defaults];

        if (![fm fileExistsAtPath:applicationSupportFolderPath]) {
            if (![fm createDirectoryAtPath:applicationSupportFolderPath withIntermediateDirectories:YES attributes:nil error:nil])
                return nil;
        }


        // The magic happens here!
        [LocationChangeHandler swizzle];

        // load Nib File
        if (![self loadMyNibFile]) {
            return nil;
        }

        // Initialize the WebView
        [webview setFrameLoadDelegate: self];
        [webview setDrawsBackground: NO];

        // create the WH Api
        api = [WHApi make];

        NSLog(@"WHController::init() panel= %@", self.panel);
    }
    return self;
}

- (void)showHUDForWebView:(WebView *)masterWebview
                 andFrame:(WebFrame *)frame
{

    // Set the master WebView such that we can refer to it
    // later
    api.masterWebFrame = frame;
    api.masterWebView = masterWebview;

    // remove all tabs
    for (NSTabViewItem *tvItem in [tabview tabViewItems]) {
        [tabview removeTabViewItem: tvItem];
    }

    // create the tabs for each title in dict
    for (NSString *title in order) {
        NSTabViewItem *tvItem = [[NSTabViewItem alloc] init];

        [tvItem setLabel: title];
        [tvItem setView: webview];

        [tabview addTabViewItem:tvItem];
    }

    [tabview selectTabViewItemAtIndex: 0];
    [panel setIsVisible: YES];
}

/**********************************************************************
 * WebKit frameLoadDelegate Methods
 */
- (void)webView:(WebView *)sender
didClearWindowObject:(WebScriptObject *)windowObject
            forFrame:(WebFrame *)frame
{
    NSLog(@"webView:didClearWindowObject:forFrame:");

    // set it to the HUD panel wso
    [windowObject setValue:api forKey:@"HUD"];
    [windowObject setValue:@"Muh Ha Hurz" forKey:@"foobar"];
}

/**********************************************************************
 * NSTabView Delegate Methods
 */
- (void)tabView:(NSTabView *)tabView
didSelectTabViewItem:(NSTabViewItem *)tabViewItem
{
    NSLog(@"Selected tab %@", tabViewItem);

    NSString *url = [urls objectForKey: [tabViewItem label]];
    NSLog(@"URL to load: %@", url);

    [[webview mainFrame] loadRequest:[NSURLRequest
                      requestWithURL:[NSURL URLWithString: url]]];
}

/**********************************************************************
 * Version etc (WTF??)
 */
+ (NSString *)version
{
    return [[NSBundle bundleWithIdentifier:BundleIdentifier]
                objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
}

+ (NSString *)userAgent
{
    return [NSString stringWithFormat:UserAgentFormat, [WHController version]];
}

@end

/* vim: set ts=4 sw=4 expandtab: */
